<?php

namespace App\Console\Commands;

use App\Models\Gift;
use App\Models\MoneyLog;
use App\Models\PointLog;
use Carbon\Carbon;
use Illuminate\Console\Command;

class UpdateMoney extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'money:update';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '定时更新津贴';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $start_time = new Carbon('first day of last month');
        $end_time = new Carbon('last day of last month');
        $month_string = $start_time->year . '年' . $start_time->month . '月';

        $start_time = $start_time->toDateString();
        $end_time = $end_time->toDateString();
//        dd($start_time);
        $point_logs = PointLog::query()->whereBetween('created_at', [$start_time, $end_time])->get();
        $result = [];
        if (!empty($point_logs)) {
            foreach ($point_logs as $point_log) {
                /** @var \App\Models\PointLog $point_log */
                if (isset($result[$point_log->user_id])) {
                    $result[$point_log->user_id] += $point_log->point;
                } else {
                    $result[$point_log->user_id] = $point_log->point;
                }
            }
            foreach ($result as $key => $value) {
                $insert['user_id'] = $key;
                $insert['money'] = $value * config('gift_ratio') * 0.01;
                $insert['date'] = $month_string;
                $insert['name'] = $month_string . "个人业绩津贴";
                $insert['order_no'] = "G" . date('YmdHis') . random_int(1000, 9999);
                $insert['send'] = 0;
                $gift = Gift::query()->where('user_id', $key)->where('date', $month_string)->first();
                if (empty($gift)) {
                    $gift = Gift::create($insert);
                    for ($i = 1; $i <= 6; $i++) {
                        $month = new Carbon('first day of this month');
                        $pay_at = $month->addMonth($i);
                        $money['user_id'] = $gift->user_id;
                        $money['order_no'] = $gift->order_no;
                        $money['money_no'] = "M" . date('YmdHis') . random_int(1000, 9999);
                        $money['type'] = 'gift';
                        $money['name'] = $month_string . "个人业绩津贴";
                        $money['money'] = $gift->money / 6;
                        $money['pay_at'] = $pay_at;
                        $money['change_type'] = true;
                        MoneyLog::create($money);
                    }
                }
            }
        }

    }
}
